import { Module } from 'vuex'
import { categoriesModuleType, GlobalDataProps } from '@/store/storeType'
import { getFn, putFn } from '@/store/store_actions_axiosFn'
import { findCat_name } from '@/hooks/useFindCat_nameFn'
import useCategoriesDeleteFn from '@/hooks/useCategoriesDeleteFn'
import useCategoriesList from '@/hooks/useAddCategoriesList'
import useAddIsShow from '@/hooks/useAddIsShow'
import axios from 'axios'

const categoriesModule: Module<categoriesModuleType, GlobalDataProps> = {
  state: () => ({
    categoriesPageObj: {}
  }),
  mutations: {
    getCategoriesPage (state, data) {
      const { pagenum } = data.data.data

      useAddIsShow(data.data.data.result.map((item: any, index: number) => {
        item.indexNum = index + 1
        return item
      }))

      state.categoriesPageObj[pagenum] = data.data.data
    },
    putCategoriesName(state, data) {
      if (data?.status && data.data.data) {
        for (const key in state.categoriesPageObj) {
          findCat_name(data.data.data, state.categoriesPageObj[key].result)
        }
      }
    },
    postCategories(state, data) {
      const { cat_id, resData, pageNum } = data
      useCategoriesList(state.categoriesPageObj[pageNum].result, resData, cat_id)
    },
    CategoriesDelete(state, data = {}) {
      const { pageNum, cat_id } = data
      state.categoriesPageObj[pageNum].result = useCategoriesDeleteFn(state.categoriesPageObj[pageNum].result, cat_id)
    }
  },
  actions: {
    getCategoriesPage ({ commit }, parmas = {}) {
      return getFn('categories', 'getCategoriesPage', commit, parmas)
    },
    putCategoriesName ({ commit }, putData) {
      return putFn(`categories/${putData.cateId}`, {cat_name: putData.cat_name}, 'putCategoriesName', commit)
    },
    async postCategories ({ commit }, postData) {
      const { cat_level, cat_name, cat_pid, cat_id, pageNum } = postData
      const res = await axios.post('categories', {
        cat_level, cat_name, cat_pid
      })
      if (res?.status === 200) {
        commit('postCategories', { resData: res.data.data, cat_id, pageNum })
      }
      return res
    }
  }
}

export default categoriesModule